package com.xteam.ecsystem.service.front;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xteam.ecsystem.dao.IFrontCartDao;
import com.xteam.ecsystem.dao.IFrontLogCouponDao;
import com.xteam.ecsystem.dao.IFrontOrderCouponDao;
import com.xteam.ecsystem.dao.IFrontOrderDao;
import com.xteam.ecsystem.dao.IFrontOrderLogDao;
import com.xteam.ecsystem.dao.IFrontUserCouponDao;
import com.xteam.ecsystem.entities.BaseCartInfo;
import com.xteam.ecsystem.entities.BaseMemeberCoupon;
import com.xteam.ecsystem.entities.BaseModePayment;
import com.xteam.ecsystem.entities.BaseOrderGoods;
import com.xteam.ecsystem.entities.BaseOrderInfo;
import com.xteam.ecsystem.entities.BaseOrderUsingcoupon;
import com.xteam.ecsystem.entities.BaseReceiveAddress;
import com.xteam.ecsystem.utils.PageCenterStation;
import com.xteam.ecsystem.utils.StringUtil;

@Service
public class FrontOrderService {
	
	@Autowired
	private IFrontOrderDao ifoDao;
	
	@Autowired
	private IFrontOrderLogDao ifolDao;
	
	@Autowired
	private IFrontCartDao ifcDao;
	
	@Autowired
	private IFrontUserCouponDao ifucDao;
	
	@Autowired
	private IFrontLogCouponDao iflcDao;
	
	@Autowired
	private IFrontOrderCouponDao ifocDao;
	
	/**
	 * 
	 * 根据用户ID返回订单列表
	 * @author ls
	 * @param pageIndex
	 * @param pageSize
	 * @param memberId
	 * @return
	 */
	public PageCenterStation<?> getOrderListByMemberId(int pageIndex, int pageSize,
			String memberId) {
		return ifoDao.getOrderListByMemberId(pageIndex, pageSize, memberId);
	}
	
	/**
	 * 
	 * 获取变化的价格
	 * @author ls
	 * @param userId
	 * @return
	 */
	public List<?> getPriceChange(String userId) {
		return ifoDao.getPriceChange(userId);
	}

	/**
	 * 
	 * 获取邮费信息
	 * @author ls
	 * @return
	 */
	public List<?> getPostAgeList() {
		return ifoDao.getPostAgeList();
	}

	/**
	 * 用户中心 - 取消订单
	 * @author liuzhi Mar 28, 2013
	 * @param orderId
	 */
	public void saveCancelOrder(String orderId, String lolUser, String lolAddress){
		this.ifoDao.saveCancelOrder(orderId);
		
		// 保存订单日志
		this.ifolDao.saveOrderLog("取消订单", orderId, "前端用户", lolUser, lolAddress, new Date(),
				"前端用户取消订单");
	}
	
	/**
	 * 根据用户ID获得可被合并的订单列表
	 * @author liuzhi Mar 29, 2013
	 * @param userId
	 * @return
	 */
	public List<?> getMergeOrders(String userId){
		return this.ifoDao.getMergeOrders(userId);
	}
	
	/**
	 * 根据订单编号获得订单信息
	 * @author liuzhi Mar 29, 2013
	 * @param orderId
	 * @return
	 */
	public BaseOrderInfo getOrderInfo(String orderId){
		return this.ifoDao.getOrderInfo(orderId);
	}
	
	/**
	 * 保存合并订单
	 * @author liuzhi Mar 29, 2013
	 * @param mainOrderInfo
	 * @param fellowOrderInfo
	 * @return
	 */
	public boolean saveMergeOrders(BaseOrderInfo mainOrderInfo, BaseOrderInfo fellowOrderInfo){
		return this.ifoDao.saveMergeOrders(mainOrderInfo, fellowOrderInfo);
	}

	/**
	 * 根据订单编号获得订购商品列表
	 * @author liuzhi Mar 29, 2013
	 * @param orderId
	 * @return
	 */
	public List<?> getOrderGoods(String orderId){
		return this.ifoDao.getOrderGoods(orderId);
	}
	
	/**
	 * 
	 * 获取支付方式信息
	 * @author ls
	 * @param type
	 * @return
	 */
	public List<?> getPayModeList(int type) {
		return ifoDao.getPayModeList(type);
	}

	/**
	 * 
	 * 是否支持货到付款
	 * @author ls
	 * @param braDistrict
	 * @return
	 */
	public boolean isCashOnDelivery(String braDistrict) {
		return ifoDao.isCashOnDelivery(braDistrict);
	}

	/**
	 * 
	 * 通过支付方式ID获取支付方式信息
	 * @author ls
	 * @param id
	 * @return
	 */
	public BaseModePayment getPayModeById(String id) {
		return ifoDao.getPayModeById(id);
	}
	
	/**
	 * 保存订单中的收货人信息
	 * @author liuzhi Apr 3, 2013
	 * @param boiObj
	 */
	public void saveOrderConsignee(BaseOrderInfo boiObj){
		this.ifoDao.saveOrderConsignee(boiObj);
	}
	
	/**
	 * 保存订单日志
	 * @author liuzhi 2014-1-9
	 * @param lolOtype
	 * @param lolOrder
	 * @param lolUtype
	 * @param lolUser
	 * @param lolAddress
	 * @param lolTime
	 * @param lolOremark
	 */
	public void saveOrderLog(String lolOtype, String lolOrder, String lolUtype,
			String lolUser, String lolAddress, Date lolTime, String lolOremark){
		ifolDao.saveOrderLog(lolOtype, lolOrder, lolUtype, lolUser, lolAddress, lolTime, lolOremark);
	}
	
	/**
	 * 前端首页 - 用户查询订单
	 * @author liuzhi Apr 24, 2013
	 * @param boiOsn
	 * @return
	 */
	public BaseOrderInfo getOrderByBoiOsn(String boiOsn){
		return this.ifoDao.getOrderByBoiOsn(boiOsn);
	}

	/**
	 * 查询用户可用的购物券
	 * 
	 * 符合以下条件即可查询相应的购物券：
	 *  1、系统已开启购物券功能
	 * 	2、登录用户
	 * 	3、用户已拥有不同数额的购物券（一张或多张）
	 * 	4、符合购物券使用规则
	 * 
	 * 下单时若使用购物券：
	 * 	1、一次只允许使用一张购物券
	 * 	2、插入购物券使用日志
	 *  3、用户购物券数量执行减少
	 * 
	 * @author liuzhi 2014-1-3
	 * @param userId
	 * @param goodsTotal
	 * @return
	 */
	public String getUserCoupons(String userId, String goodsTotal) {
		return this.ifoDao.getUserCoupons(userId, goodsTotal);
	}

	/**
	 * 保存订单信息
	 * @author liuzhi 2014-1-9
	 * @param bra
	 * @param userId
	 * @param yunfei
	 * @param couponPrice
	 * @param couponId
	 * @param remark
	 * @param payMode
	 * @param ip
	 * @return 
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> saveUserOrder(BaseReceiveAddress bra, String userId, double yunfei, 
			double couponPrice, String couponId, String remark, String payMode, String ip) {
		// 保存返回的对象
		Map<String, Object> map = new HashMap<String, Object>();
		// 保存商品列表
		List<BaseOrderGoods> bogs = new ArrayList<BaseOrderGoods>();
		// 删除商品类别
		List<BaseCartInfo> bcis = new ArrayList<BaseCartInfo>();
		// 区别用户是否使用了购物券
		boolean isUsed = false;
		
		try {
			// 1、创建新订单
			BaseOrderInfo boi = new BaseOrderInfo();
			
			boi.setBoiMember(userId);
			boi.setBoiOsn(StringUtil.getSerTimeNum());
			// TODO 若选择的是在线支付或第三方支付接口支付，则需调整此处！
			
			boi.setBoiOrder(0);
			boi.setBoiPay(0);
			boi.setBoiShip(0);
			boi.setBoiCountry(bra.getBraCountry());
			boi.setBoiProvince(bra.getBraProvince());
			boi.setBoiCity(bra.getBraCity());
			boi.setBoiDistrict(bra.getBraDistrict());
			boi.setBoiConsignee(bra.getBraConsignee());
			boi.setBoiDetail(bra.getBraDetail());
			boi.setBoiZipcode(bra.getBraZipcode());
			boi.setBoiMobile(bra.getBraMobile());
			boi.setBoiPhone(bra.getBraPhone());
			boi.setBoiBest(bra.getBraTime());
			boi.setBoiOtime(new Date());
			boi.setBoiGpay(ifcDao.getCartTotal(userId));
			
			if (yunfei > 0){
				boi.setBoiSpay(yunfei);
			}else{
				boi.setBoiSpay(0.0);
			}
			
			if (couponPrice > 0){
				boi.setBoiCouponpay(couponPrice);
				isUsed = true;
			}else{
				boi.setBoiCouponpay(0.0);
			}
			
			// 订单实付总额
			boi.setBoiTpay(boi.getBoiGpay() + yunfei - couponPrice);
			boi.setBoiUremark(remark);
			boi.setBoiDeliverymode("店主配送");
			
			BaseModePayment bmp = getPayModeById(payMode);
			boi.setBoiPaymode(bmp.getBmpType());
			boi.setBoiPaymodename(bmp.getBmpName());
			
			// 2、保存订单信息
			boi = this.ifoDao.saveOrderInfo(boi);
			
			// 3、读取用户订购的商品列表
			List goodsList = ifcDao.getAllGoodsByUser(boi.getBoiMember());
			if(goodsList != null && goodsList.size() > 0){
				for (int i = 0 ,j = goodsList.size(); i < j; i++){
					BaseCartInfo bci = (BaseCartInfo) goodsList.get(i);
					BaseOrderGoods bog = new BaseOrderGoods();
					bog.setBogOid(boi.getBoiId());
					bog.setBogGid(bci.getBciGoods());
					bog.setBogName(bci.getBciName());
					bog.setBogMarket(bci.getBciMarket());
					bog.setBogPrice(bci.getBciPrice());
					bog.setBogAttribute(bci.getBciAttrname());
					bog.setBogAttprice(bci.getBciAttprice());
					bog.setBogNumber(bci.getBciNumber());
					bog.setBogTotal(bci.getBciTotal());
					
					bogs.add(bog);
					bcis.add(bci);
				}
				
				// 4、保存订购商品信息
				this.ifoDao.saveOrderGoods(bogs);
				
				// 5、删除购物车中的商品
				this.ifoDao.deleteCartGoods(bcis);
			}
			
			// 6、保存订单日志
			saveOrderLog("新增", boi.getBoiId(), "前端用户", boi.getBmbNick(), ip, new Date(), remark);
			
			if (isUsed) {
				// 7、保存订单与使用券关联表(一次只能使用一张购物券)
				BaseOrderUsingcoupon buc = new BaseOrderUsingcoupon();
				buc.setBouOrder(boi.getBoiId());
				buc.setBouCoupon(couponId);
				buc.setBouPrice(couponPrice);
				buc.setBouNumber(1);
				this.ifocDao.saveOrderUsingCoupon(buc);
				
				// 8、修改用户购物券表(购物券数量大于1，实行修改，反之，执行删除)
				BaseMemeberCoupon bmc = this.ifucDao.getBmcInfo(userId, couponId);
				
				if(bmc.getBmcNumber() > 1){
					bmc.setBmcNumber(bmc.getBmcNumber() - 1);
					this.ifucDao.updateBmcInfo(bmc);
				}else{
					this.ifucDao.deleteBmcinfo(bmc);
				}
				
				// 9、保存购物券使用日志
				this.iflcDao.saveCouponLog(userId, couponId, couponPrice, -1, "使用购物券，订单：" + boi.getBoiId());
			}
			
			map.put("isSucc", true);
			map.put("orderInfo", boi);
		} catch (Exception e) {
			map.put("isSucc", false);
			map.put("orderInfo", null);
			e.printStackTrace();
		}
		
		return map;
	}

}
